#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QDir>
#include <QFileInfoList>
#include <QCamera>
#include <QCameraInfo>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QMessageBox>
#include <QPixmap>
#include <QDateTime>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QString>
#include "contentwidget.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    www.show();
    // 获取摄像头设备
    QList<QCameraInfo> infos = QCameraInfo::availableCameras();
    QString camera = infos.value(0).deviceName();

    // 打开摄像头
    ca = new QCamera(camera.toUtf8(), this);
    ui->camera->show();

    QCameraViewfinder *v2 = new QCameraViewfinder(ui->camera);
    v2->resize(ui->camera->size());
    ca->setViewfinder(v2);
    v2->show();
    ca->start();

    // 初始化摄像头截图对象
    capture = new QCameraImageCapture(ca);
    connect(capture, &QCameraImageCapture::imageCaptured, this, &MainWindow::onImageCaptured);

    savePath = "D:/project_img/";
    if (!savePath.endsWith("/")) {
        savePath += "/";
    }

    // 创建定时器，用于定时截图
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::captureAndOpenImage);
    timer->start(5000);  // 5秒触发一次
    //captureAndOpenImage();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::timerStart()
{
    timer->start(5000);  // 5秒触发一次
}

void MainWindow::timerStop()
{
    timer->stop();
}
void MainWindow::captureAndOpenImage()
{
    // 截取图片
    QString fileName = QDateTime::currentDateTime().toString("yyyyMMddHHmmss") + ".jpg";
    capture->capture(savePath + fileName);
}

void MainWindow::onImageCaptured(int id, const QImage &image)
{
    // 保存截图到文件
    QString fileName = QDateTime::currentDateTime().toString("yyyyMMddHHmmss") + ".jpg";
    image.save(savePath + fileName);

    // 显示截图
    QPixmap pix(savePath + fileName);
    ui->label->setPixmap(pix.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));

    // 自动识别最新图片
    recognizeImage(fileName);

    // 检查文件夹中的图片数量，如果超过20张，删除最旧的10张
    deleteOldImages();
}

void MainWindow::recognizeImage(const QString &fileName)
{
    www.on_uploadImageButton_clicked(savePath + fileName);
    storeAndDisplayRecognizedText(www.text);
}

void MainWindow::deleteOldImages()
{
    QDir dir(savePath);
    QFileInfoList fileList = dir.entryInfoList(QDir::Files, QDir::Time);

    if (fileList.size() > 20)
    {
        // 删除最旧的10张图片
        for (int i = 0; i < 10; ++i)
        {
            if (i < fileList.size())
            {
                QFile::remove(fileList.last().absoluteFilePath());
                fileList.removeLast();
            }
        }
    }
}

void MainWindow::storeAndDisplayRecognizedText(QString &text)
{
    if (text.length() == 9)
    {
        for (int i = 0; i < 9; ++i)
        {
            QChar currentChar = text.at(i);
            int row = i / 3;
            int col = i % 3;

            if (currentChar == '0' || currentChar == 'o' || currentChar == 'O' || currentChar == '\u3007' || currentChar == '\u25CC')
            {
                recognizedChars[row][col] = '2';
            }
            else if (currentChar == 'x' || currentChar == 'X' || currentChar == '\u00D7')
            {
                recognizedChars[row][col] = '1';
            }
            else
            {
                recognizedChars[row][col] = '0';
            }
        }

        qDebug() << "Recognized Characters (3x3 Array):";
        for (int i = 0; i < 3; ++i)
        {
            QString rowString;
            for (int j = 0; j < 3; ++j)
            {
                rowString += recognizedChars[i][j];
                rowString += " ";
            }
            qDebug() << rowString;
        }
        timerStop();
    }
    else
    {
        qDebug() << "Warning: Recognized text length is not 9. Text: " << text;
    }
}
